package club.xcgame520.okhttp;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Created by Administrator on 2017/8/25 0025.
 */

public class OkHttpUtil {

    /**
     * 如果不需要验证服务器端证书
     *
     * @return
     */
    public static SSLSocketFactory getDefaultSSLSocketFactory() {

        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{getDefaultX509TrustManager()}, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            //
            e.printStackTrace();
        } catch (KeyManagementException e) {
            //
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 如果不需要验证服务器端证书
     *
     * @return
     */
    public static X509TrustManager getDefaultX509TrustManager() {

        X509TrustManager x509TrustManager = new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        return x509TrustManager;
    }


    public static int checkNetworkConnectivity(Context context) {

        //获取这个权限需要在manifest中添加"android.permission.ACCESS_NETWORK_STATE"权限
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

        if (networkInfo != null) {
            //2.获取当前网络连接的类型信息
            int networkType = networkInfo.getType();
            if (ConnectivityManager.TYPE_WIFI == networkType) {
                return 2;
                //当前为wifi网络
            } else if (ConnectivityManager.TYPE_MOBILE == networkType) {
                return 1;
                //当前为mobile网络
            }
        }

        return 0;

    }


}
